package com.kenans.contorller;

import com.kenans.common.JsonResult;
import com.kenans.entity.User;
import com.kenans.service.UserService;
import com.kenans.util.JsonUtil;
import com.kenans.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.jws.soap.SOAPBinding;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author KENANS
 * @date 2020-8-26 14:12
 * @Version 1.0
 */
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;


    /**
     * 前端的数据要，code 和 info
     * 要传过去密码错误还是账号错误！
     * 这个login就要根据用户名去取user了
     */
    @RequestMapping("/login.do")
    @ResponseBody // 这个注解是处理返回的对象，变成json数据
    public JsonResult login(String tel, String password, HttpSession session) {
        User user = new User(tel, password);
        JsonResult jsonResult = null;

        try {
            User login = userService.login(user);
            session.setAttribute(StrUtil.LOGINUSER, login);
            // 这里的new JsonResult 已经重复了很多次了，封装!!!!。
            jsonResult = JsonUtil.createJson(1, login);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult = JsonUtil.createJson(0, e.getMessage());
        }
        return jsonResult;
    }

    @RequestMapping("/register.do")
    @ResponseBody
    public JsonResult register(String tel, String password, String email, String invitation) {
        User user = new User(tel, password, email, invitation);

        userService.addUser(user);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode(1);
        return jsonResult;
    }

    @RequestMapping("/denglu.do")
    @ResponseBody
    public JsonResult loginSubmit(HttpSession session) {
        User user = (User)session.getAttribute("loginUser");
        return new JsonResult(1, user);
    }
}
